
var WEBSOCKET_MAP = new Map();

console.info("Service Worker is runing !")

var FUN_MAP = new Map();
FUN_MAP.set("connection", function (data) {
    connect(data.name, data.ip, data.port, data.path, data.onOpen, data.onMessage)
})

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.type === 'BET_CALL_METHOD') {
        if (FUN_MAP.has(message.action)) {
            FUN_MAP.get(message.action)(message.data)
        }
        sendResponse({ result: "ok" });
    }
    if (message.from === "content_script" && message.action === "page_message") {
        console.log("收到页面消息：", message.data);
        // 可回复
        sendResponse({ status: "ok", data: jsList });
    }
    return true;
});

var jsList = []

// 这里监控所有JS请求
// 不同的平台需要在这里修改实现
// megadice.com 获取指定JS请求路径 并通过chrome.runtime.onMessage.addListener 返回给 content_script -> 注入js
chrome.webRequest.onCompleted.addListener(
    function (details) {
        if (details.type === "script") {
            if (details.url.includes("layout-") && details.url.includes("megadice")) {
                console.log("JS 请求完成：", details.url, "由：", details.initiator || details.documentUrl);
                if (jsList.length < 2) {
                    jsList.push(details.url);
                } else {
                    jsList = []
                    jsList.push(details.url);
                }
            }
        }
    },
    { urls: ["<all_urls>"] },
    []
);



function connect(name, ip, port, path, onOpen, onMessage) {
    let websocket = null;
    if (WEBSOCKET_MAP.has(name)) {
        websocket = WEBSOCKET_MAP.get(name);
    }
    websocket = new WebSocket(`ws:///${ip}:${port}/${path}`);
    websocket.name = name;
    websocket.onopen = (event) => {
        websocket.intervalId = setInterval(() => {
            websocket.send("Ping")
        }, 20 * 1000)
        onOpen()
    };
    websocket.onmessage = (event) => {
        onMessage(event.data)
    };
    websocket.onclose = (event) => {
        clearInterval(websocket.intervalId)
        console.log(`Websocket[${websocket.name}] connection closed`);
        WEBSOCKET_MAP.delete(websocket.name)
    };
}

function disconnect(name) {
    if (!WEBSOCKET_MAP.has(name)) {
        return;
    }
    WEBSOCKET_MAP.get(name).close();
}


